/**
 * @Title: UploadServlet.java
 * @Copyright (C) 2017 龙图软件
 * @Description:
 * @Revision History:
 * @Revision 1.0 2017-12-7  yuanchunci
 */
 

package com.ycc.fileTransfer.controller;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.RandomAccessFile;
import java.io.Writer;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import java.util.UUID;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.FileSystemXmlApplicationContext;

import com.ycc.fileTransfer.service.FileTransferService;
import com.ycc.uitl.ThumbnailUitl;
import com.ycc.uitl.Tool;

/**
 * @ClassName: UploadServlet
 * @Description: Description of this class
 * @author <a href="mailto:XXX@qq.com">yuanchunci</a>于 2017-12-7 下午5:45:13
 */

public class UploadServlet extends HttpServlet{
	public void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException
    {
		ApplicationContext context = new FileSystemXmlApplicationContext( new String []{
				"classpath:spring-mvc.xml",	"classpath:spring-mybatis.xml"});
		FileTransferService fileTransferService = (FileTransferService) context.getBean("FileTransferService");
		  String uuid = UUID.randomUUID().toString().replaceAll("-", "");
		   String path =this.getServletContext().getRealPath("/");//返回Servlet上下文路径  
		//向控制台输出文件的内容长度
				System.out.println(request.getContentLength());
				//如果有内容
				if (request.getContentLength() > 297) {

					 request.setCharacterEncoding("UTF-8");  
					//==================开始处理文件===================
					System.out.println(request.getCharacterEncoding());
					//接收上传文件内容中临时文件的文件名
			        String tempFileName = new String("tempFileName.txt");
			        //tempfile 对象指向临时文件
			        File tempFile = new File(request.getRealPath("/")+tempFileName);
			        //outputfile 文件输出流指向这个临时文件
			        FileOutputStream outputStream = new FileOutputStream(tempFile);
			        //得到客服端提交的所有数据
			        InputStream fileSourcel = request.getInputStream();
			        //将得到的客服端数据写入临时文件
			        byte b[] = new byte[1000];
			        int n ;
			        while ((n=fileSourcel.read(b))!=-1){
			            outputStream.write(b,0,n);
			        }

			        //关闭输出流和输入流
			        outputStream.close();
			        fileSourcel.close();

			        //randomFile对象指向临时文件
			        RandomAccessFile randomFile = new RandomAccessFile(tempFile,"r");
			        //读取临时文件的前三行数据
			        randomFile.readLine();
			        randomFile.readLine();
			        randomFile.readLine();
			        //读取临时文件的第四行数据，这行数据中包含了文件的路径和文件名
			        String filePath = randomFile.readLine();
			        //得到文件名
			        System.out.println(filePath);
			        int position = filePath.lastIndexOf("filename");
			        String filename =Tool.codeString(filePath.substring(position+10,filePath.length()-1));
			        //重新定位读取文件指针到文件头
			        randomFile.seek(0);
			        //得到第四行回车符的位置，这是上传文件数据的开始位置
			        long  forthEnterPosition = 0;
			        int forth = 1;
			        while((n=randomFile.readByte())!=-1&&(forth<=5)){
			            if(n=='\n'){
			                forthEnterPosition = randomFile.getFilePointer();
			                forth++;
			            }
			        }

			        //生成上传文件的目录
			        File fileupLoad = new File(request.getRealPath("/"),"upLoad");
			        fileupLoad.mkdir();
			        //saveFile 对象指向要保存的文件
			        File saveFile = new File(request.getRealPath("/")+"\\upLoad",uuid+filename);
			        RandomAccessFile randomAccessFile = new RandomAccessFile(saveFile,"rw");
			        //找到上传文件数据的结束位置，即倒数第四行
			        randomFile.seek(randomFile.length());
			        long endPosition = randomFile.getFilePointer();
			        System.out.println(endPosition);
			        int j = 1;
			        while((endPosition>=0)&&(j<=2)){
			            endPosition--;
			            randomFile.seek(endPosition);
			            if(randomFile.readByte()=='\n'){
			                j++;
			            }
			        }
			        endPosition=endPosition-1;
			        //从上传文件数据的开始位置到结束位置，把数据写入到要保存的文件中
			        randomFile.seek(forthEnterPosition);
			        long startPoint = randomFile.getFilePointer();
			        while(startPoint<endPosition){
			            randomAccessFile.write(randomFile.readByte());
			            startPoint = randomFile.getFilePointer();
			        }
			        //关闭文件输入、输出
			        randomAccessFile.close();
			        randomFile.close();
			        tempFile.delete();
					//==================处理文件结束===================
					//向控制台输出文件上传成功
					System.out.println("File upload success!");
				} 
				else 
				{
					//否则显示失败，
					System.out.println("No file!");
					//向Unity返回一个Fasle字符串
					Writer out=response.getWriter();
					out.write("false");
					out.close();
				}
			}
		/*ApplicationContext context = new FileSystemXmlApplicationContext( new String []{
				"classpath:spring-mvc.xml",	"classpath:spring-mybatis.xml"});
		FileTransferService fileTransferService = (FileTransferService) context.getBean("FileTransferService");
		  String uuid = UUID.randomUUID().toString().replaceAll("-", "");
		   String path =this.getServletContext().getRealPath("/");//返回Servlet上下文路径  
	       path = path.substring(0, path.length() - 1);//在Servlet上下文路径的最后包含一个"."号，所以这里将它去除  
	       path = path + "\\WEB-INF\\";//将路径放置在项目下的WEB-INF目录下  
	       path = path + "uploadLocation.properties";//这里就是我的properties文件  
	       FileInputStream input = new FileInputStream(path);  
	        Properties pro = new Properties();
	   	  String uploadPath="";
	  	   try {
	  	        pro.load(input);
	  	 	} catch (IOException e) {
	  	 		e.printStackTrace();
	  	 	}finally{
	  	 		input.close();
	  	 	}
	          if(pro!=null){
	            uploadPath=pro.getProperty("uploadUrl");
	            System.out.println(uploadPath);
	          }
	          File fileDir = new File(uploadPath);
	          if(!fileDir.exists()){
	          	fileDir.mkdir();
	          }
	          //向控制台输出文件的内容长度
	          System.out.println(request.getContentLength());
	          System.out.println(request.getRealPath("/"));
	      
	          String tempFileName = new String("tempFileName.txt");
	          File tempFile = new File(request.getRealPath("/")+"\\"+tempFileName);
	          //outputfile 文件输出流指向这个临时文件
	            FileOutputStream outputStream = new FileOutputStream(tempFile);
	          //outputfile 文件输出流指向这个临时文件
	          InputStream fileSourcel = request.getInputStream();
	        //将得到的客服端数据写入临时文件
	          byte b[] = new byte[fileSourcel.available()];
	          int n ;
	          while ((n=fileSourcel.read(b))!=-1){
	              outputStream.write(b,0,n);
	          }

	          //关闭输出流和输入流
	          outputStream.close();
	          fileSourcel.close();
	          System.out.println(fileSourcel);
	          
	          RandomAccessFile randomFile = new RandomAccessFile(tempFile,"r");
	            //读取临时文件的前三行数据
	            randomFile.readLine();
	            randomFile.readLine();
	            randomFile.readLine();
	            //读取临时文件的第四行数据，这行数据中包含了文件的路径和文件名
	            String filePath = randomFile.readLine();
	            //得到文件名
	            System.out.println(filePath);
	            
	            int position = filePath.lastIndexOf("filename");
	            String filename =Tool.codeString(filePath.substring(position+10,filePath.length()-1));
	            //重新定位读取文件指针到文件头
	            randomFile.seek(0);
	            //得到第四行回车符的位置，这是上传文件数据的开始位置
	            long  forthEnterPosition = 0;
	            int forth = 1;
	            while((n=randomFile.readByte())!=-1&&(forth<=4)){
	                if(n=='\n'){
	                    forthEnterPosition = randomFile.getFilePointer();
	                    forth++;
	                }
	            }
	            File saveFile = new File(uploadPath,uuid+filename);
	            RandomAccessFile randomAccessFile = new RandomAccessFile(saveFile,"rw");
	            //找到上传文件数据的结束位置，即倒数第四行
	            randomFile.seek(randomFile.length());
	            long endPosition = randomFile.getFilePointer();
	            int j = 1;
	            while((endPosition>=0)&&(j<=4)){
	                endPosition--;
	                randomFile.seek(endPosition);
	                if(randomFile.readByte()=='\n'){
	                    j++;
	                }
	            }

	            //从上传文件数据的开始位置到结束位置，把数据写入到要保存的文件中
	            randomFile.seek(forthEnterPosition);
	            long startPoint = randomFile.getFilePointer();
	            while(startPoint<endPosition){
	                randomAccessFile.write(randomFile.readByte());
	                startPoint = randomFile.getFilePointer();
	            }
	            //关闭文件输入、输出
	            randomAccessFile.close();
	            randomFile.close();
	            tempFile.delete();
	            System.out.println("File upload success!");
	            if(filename != null){
	            	Map p=new HashMap();
			        Map result=new HashMap();
			        String thumpath=uploadPath+"/thum";
	                String typesStr="mpg,mpeg,avi,rm,rmvb,mov,wmv,asf,dat(VCD),asx,wvx,mpe,mpa,mp4,mp3";
				    String type= Arrays.toString(ImageIO.getReaderFormatNames())+typesStr;
					String suffix=null;
//			        result= ThumbnailUitl.thumbnail(file,uploadPath, uploadPath,uuid);
			        p.put("content", "");
			        p.put("filepath", uploadPath+"/"+uuid+filename);
					p.put("id", uuid);
					filename = new String(filename.getBytes("iso8859-1"), "UTF-8");
					p.put("fileName",filename);
					if(filename.indexOf(".") > -1) {
					      suffix = filename.substring(filename.lastIndexOf(".") + 1);
					 }
					if(type.indexOf(suffix)>-1){
						p.put("ThumbnailName", path+"/"+uuid+filename.substring(0, filename.indexOf(suffix))+"jpg");
					}else{
						p.put("ThumbnailName", "");

					}
					File thumFile=new File(uploadPath+"/"+uuid+filename);
					p.put("ThumbnailData", ThumbnailUitl.thumbnail(request,thumFile, uploadPath, uploadPath,uuid));
					try {
						fileTransferService.insertOne(p);
					} catch (Exception e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}// 这里就把获得的byte字节文件数据做操作
//			   }
				    
	            }
//	          FileOutputStream outputStream = new FileOutputStream(tempFile);
//			if(!file.isEmpty()) {  
//			        Map p=new HashMap();
//			        Map result=new HashMap();
//			        String path=uploadPath+"/thum";
//			        String typesStr="mpg,mpeg,avi,rm,rmvb,mov,wmv,asf,dat(VCD),asx,wvx,mpe,mpa,mp4,mp3";
//					String type= Arrays.toString(ImageIO.getReaderFormatNames())+typesStr;
//					String suffix=null;
//			        result= ThumbnailUitl.thumbnail(file,uploadPath, uploadPath,uuid);
//			        p.put("content", "");
//			        p.put("filepath", result.get("filepath"));
//					p.put("id", uuid);
//					p.put("fileName",file.getOriginalFilename());
//					if(file.getOriginalFilename().indexOf(".") > -1) {
//					      suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".") + 1);
//					 }
//					if(type.indexOf(suffix)>-1){
//						p.put("ThumbnailName", path+"/"+uuid+file.getOriginalFilename().substring(0, file.getOriginalFilename().indexOf(suffix))+"jpg");
//					}else{
//						p.put("ThumbnailName", "");
//
//					}
//					//Thread.currentThread().getContextClassLoader().getResource("").getPath();
//					p.put("ThumbnailData", ThumbnailUitl.thumbnail(request,file, path, (String)result.get("filepath"),uuid));
//					fileTransferService.insertOne(p);// 这里就把获得的byte字节文件数据做操作
//			   }
//			 return "redirect:show.html";    
*/	    	
    
	
	public void doPost(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException
    {
		doGet(request,response);
        //向控制台输出文件的内容长度
        System.out.println(request.getContentLength());
        
    }
} 
